#include "netdriver.h"
#include <QTcpSocket>

NetDriver *NetDriver::obj=nullptr;
NetDriver::NetDriver(QObject *parent) : QObject(parent)
  ,client(new QTcpSocket)
{
 connect(client,&QTcpSocket::connected,this,&NetDriver::netConnected);
 connect(client,&QTcpSocket::disconnected,this,&NetDriver::netDisconnected);
 connect(client,&QTcpSocket::readyRead,this,&NetDriver::netReadSlot);//绑定收到数据的信号和槽

}

NetDriver *NetDriver::getObject()
{
if(obj == nullptr)
    obj= new NetDriver;
return obj;
}

bool NetDriver::netConnect1(QString ip, quint16 port)
{
netDisconnect();
client->connectToHost(ip,port);
return client->waitForConnected(2000);
}

void NetDriver::netConnect2(QString ip, quint16 port)
{
    netDisconnect();
    client->connectToHost(ip,port);

}

void NetDriver::netDisconnect()
{
if(client->state() == QTcpSocket::ConnectedState)
    client->disconnectFromHost();
}

bool NetDriver::netGetState()
{
return client->state() == QTcpSocket::ConnectedState ? true :false;
}

bool NetDriver::netWrite(const QByteArray &data)
{
if(!netGetState())
    return false;
qint64 len = client->write(data);//tcp发送数据
return len == data.length() ? true : false;// 如果长度相等，就说明发送成功
}



void NetDriver::netReadSlot()
{
    QByteArray data=client->readAll();
    emit netRead(data);
}
